package com.huanglj.taobaounion.ui.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.huanglj.taobaounion.model.domain.CategoriesById;
import com.huanglj.taobaounion.utils.LogUtil;
import com.huanglj.taobaounion.utils.UrlUtils;

import java.util.ArrayList;
import java.util.List;

public class LoopPagerAdapter extends PagerAdapter {

    private static final String TAG = "LoopPagerAdapter";

    List<CategoriesById.DataBean> mDataBeans = new ArrayList<>();
    private OnItemClickListener mListener;

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        int realPosition = position % mDataBeans.size();
        ImageView imageView = new ImageView(container.getContext());
        String pict_url = mDataBeans.get(realPosition).getPict_url();
        LogUtil.d(TAG,pict_url);
        //给ImageView设置宽高
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewPager.LayoutParams.MATCH_PARENT,ViewPager.LayoutParams.MATCH_PARENT);
        imageView.setLayoutParams(layoutParams);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);


        String imageUrl = UrlUtils.getCoverPath(pict_url,800);
        Glide.with(container.getContext()).load(imageUrl).into(imageView);

        container.addView(imageView);

        CategoriesById.DataBean dataBean = mDataBeans.get(realPosition);

        imageView.setOnClickListener(v -> {
            mListener.onClick(dataBean);
        });
        return imageView;
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    public void setData(List<CategoriesById.DataBean> contents) {
        mDataBeans.clear();
        mDataBeans.addAll(contents);
        notifyDataSetChanged();
        LogUtil.d(TAG,"Adapter data size :" + mDataBeans.size());
    }

    public interface OnItemClickListener {
        void onClick(CategoriesById.DataBean pict_url);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.mListener = listener;
    }
}
